<?php

/**
 * Контроллер для управления заказами
 * 
 * @author MF
 * @version 2.0
 */

require_once 'Zend/Controller/Action.php';

class Cms_OrdersController extends Zend_Controller_Action {

	function init() {
		CmsAccess::restrictModule('orders');
	}

    public function indexAction() {
//        Zend_Debug::dump($_POST);

        $orders = MF_Main::getInstance()->OrderList;

        //в качестве индексов = key
		$fNames = $orders->getFlagNames(); //русские названия
		$fBits = $orders->getFlagBits();   //номера битов
		
		$this->view->flagNames = $fNames;
    }


	public function widgetAction() {
		$orders = MF_Main::getInstance()->OrderList;
		$orderSearch = $orders->OrderSearch();

        if ((NULL !== $limit_from = $this->getRequest()->getParam('limit_from'))
			&& (NULL !== $limit_amount = $this->getRequest()->getParam('limit_amount'))) {
				$orderSearch->setLimits($limit_from,$limit_amount);
        }

        $orderSearch->flag->value = ">0"; //корзины отбрасываем
        //берем фильтр
        if( NULL !== $f_status = $this->getRequest()->getParam('f_status') ){
            if( $f_status )
                $orderSearch->flag->$f_status = 1;
        }

        if( NULL !== $f_login = $this->getRequest()->getParam('f_login') ){
            $d = "b.login";
            $orderSearch->$d = $f_login;
        }

		if ((NULL !== $from_date = $this->getRequest()->getParam('f_from'))
			&& (NULL !== $to_date = $this->getRequest()->getParam('f_to'))) {
				$orderSearch->dateFromTo($from_date,$to_date);
		}

		$orderSearch->Make();

		//формируем массив с данными
		$orders_data = array();

		//в качестве индексов = key
		$fNames = $orders->getFlagNames(); //русские названия
		$fBits = $orders->getFlagBits();   //номера битов

		$this->view->flagNames = $fNames;

		for($i=0; $i<$orderSearch->length(); $i++){
            $ordersNote = $orderSearch->item($i);
            //сформируем массив с флагами
            $users = MF_Main::getInstance()->UserList->UserSearch();
            $users->user_id = $ordersNote->user_id;
            $users->Make();
            $ordersNoteNode = 
                array(
                    array('order_date',array('id' => $ordersNote->order_id,'value' => $ordersNote->date_time)),
                    array('users_login',array('id' => $ordersNote->order_id, 'user_id' => $users->item(0)->user_id, 'value' => $users->item(0)->login."(id: ".$users->item(0)->user_id.")")),
                    array('orders_status',array('id' => $ordersNote->order_id, 'value' => $ordersNote->flagAsKey(), 
                        'flagNames' => $fNames, 'bitName' => $fBits )),
                    array('order_summa',array('id' => $ordersNote->order_id,'value' => $ordersNote->summa))
                );

            //пройдемся по флагам и, если выставлен, занести его в массив юзера
/*			foreach($fBits as $index => $c ){
				array_push($ordersNoteNode,
				    array('order_flags',
				        array('id' => $ordersNote->order_id, 'bit' => $index, 'value' => $ordersNote->flag->$index)
				));
			}*/
			array_push($ordersNoteNode, array('order_edit',array('id' => $ordersNote->order_id)));
			array_push($ordersNoteNode, array('post_print',array('id' => $ordersNote->order_id)));
            array_push($orders_data, $ordersNoteNode);
            unset($users);
		}

        $this->view->data = array('total_length' => $orderSearch->total_length(), 'data' => $orders_data);
        $this->renderScript('json.phtml');
	}

	public function goodlistAction() {
		if (NULL === $mask = $this->getRequest()->getParam('mask')) {
			throw new Zend_Controller_Action_Exception('Required param "mask"', 404);
		}

		$main = MF_Main::getInstance();
		$good_list = $main->Catalog->getById($main->OrderList->_catalog_id)->filter()
			->appendNameMaskCondition("%$mask%")->sortByName()->Make();

		$pool_list = array();

		if (trim($mask)!=='') {
			for ($l=0;$l<$good_list->length();$l++) {
				$cur_good = $good_list->item($l);
				array_push($pool_list,
					array(
						$cur_good->_content_id,
						$cur_good->name,
						$cur_good->price
					));
			}
		}

		$this->view->data = $pool_list;

		$this->renderScript('json.phtml');
	}

	public function userlistAction() {
		if (NULL === $mask = $this->getRequest()->getParam('mask')) {
			throw new Zend_Controller_Action_Exception('Required param "mask"', 404);
		}

		$user_list = array();

		$userList = MF_Main::getInstance()->UserList;
		
		$user_search = $userList->UserSearch();
		$user_search->login = "$mask%";
		$this->_addUsersToList($user_search->Make(),$user_list);
		
		$user_search = $userList->UserSearch();
		$user_search->email = "$mask%";
		$this->_addUsersToList($user_search->Make(),$user_list);
		
		/*$ret_list = array();
		foreach ($user_list as $user_id) {
			$user = $userList->getById($user_id);
			array_push($ret_list,array(
					$user->user_id,
					"{$user->name_f} {$user->name_i} {$user->name_o} (L:{$user->login} E-Mail:{$user->email})"
				));
		}*/
		
		$this->view->data = $user_list;
		$this->renderScript('json.phtml');
	}
	
	
	
	/**
	 * 
	 *
	 * @uses userListAction
	 * 
	 * @param UserSearch $searchObj
	 * @param Array $list
	 */
	private function _addUsersToList($searchObj,&$list) {
		for ($s=0;$s<$searchObj->length();$s++) {
			$user = $searchObj->item($s);
			array_push($list,array(
					$user->user_id,
					"{$user->name_f} {$user->name_i} {$user->name_o} (L: {$user->login} E-Mail: {$user->email})"
				));
		}
	}
	 
	
	public function flagAction(){

		if (NULL === $id = $this->getRequest()->getParam('id')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}

	   if (NULL === $flag = $this->getRequest()->getParam('flag')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}
		
		//опрокидываем указанный флаг
		$order = MF_Main::getInstance()->OrderList->getById($id);
		
		//обнулим все флаги
		$order->flag->nonsubmit = 0;
		$order->flag->submit = 0;
		$order->flag->inwork = 0;
		$order->flag->send = 0;
		$order->flag->cancelbyuser = 0;
		$order->flag->cancelbyadmin = 0;
		
		$order->flag->$flag = 1;//$order->flag->$flag == '0' ? '1' : '0';
		$this->view->result = $order->flag->$flag;
		$this->_helper->layout->disableLayout(); 
		echo $order->flag->$flag;
	}	
	
	public function addAction() {
		if ($this->_request->isPost()) {
			$params = $this->_request->getPost();
			
			$orderObj = MF_Main::getInstance()->OrderList;
			$order = $orderObj->addOrder($params['user_id']);
			$order->flag->submit = 1;
			$total_price = 0;
			
			for ($g=0;$g<count($params['good_id']);$g++) {
				$order->add($params['good_id'][$g],$params['good_name'][$g],$params['good_amont'][$g],$params['good_price'][$g]);
				$total_price += ($params['good_amont'][$g] * $params['good_price'][$g]);
			}
			
			$order->summa = $total_price;
			$this->renderScript('exit.phtml');
			return true;
		}
		$this->view->goods = array(
			array(
					'item_id' => '',  
					'name' => '',
					'price' => '',
					'count' => 1
				));
		$this->render('order-form');
	}
	
	
	public function editAction(){
      	$filter = new Zend_Filter_StripTags();

        $order_id = $filter->filter($this->_getParam('order_id'));

        //получаем информацию о заказе
        $order = MF_Main::getInstance()->OrderList->getById($order_id);
        
        if ($this->_request->isPost()) {
        	$params = $this->_request->getPost();
        	
        	$order->Clear();
        	
        	$total_price = 0;
			
			for ($g=0;$g<count($params['good_id']);$g++) {
				$order->add($params['good_id'][$g],$params['good_name'][$g],$params['good_amont'][$g],$params['good_price'][$g]);
				$total_price += ($params['good_amont'][$g] * $params['good_price'][$g]);
			}
			
			$order->summa = $total_price;
			
			$this->renderScript('exit.phtml');
			return true;
        } else {
	        $this->view->user_id = $order->user_id;
	        $this->view->user_name = "{$order->user->name_f} {$order->user->name_i} {$order->user->name_o} (L: {$order->user->login} E-Mail: {$order->user->email})";
	
			$goods = array();
			for ($g=0;$g<$order->length();$g++) {
				$good = $order->item($g);
				array_push($goods,
					array(
						'item_id' => $good->item_id,  
						'name' => $good->name,
						'price' => $good->price,
						'count' => $good->count
					));
			}
			$this->view->goods = $goods;
        }
		
		$this->render('order-form');
	}	
	
	public function postprintAction() {
		// FIXED реализовать вывод бланков на печать;

		if (NULL === $id = $this->getRequest()->getParam('id')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}
		$order = MF_Main::getInstance()->OrderList->getById($id);
		if(!$order){
			throw new Zend_Controller_Action_Exception('Cannot find order by id '.$id);
		}
		$user = $order->user;
		$name = $user->name_f.' '.$user->name_i.' '.$user->name_o;
		$index = str_split($user->index2,1);
		$country = $user->country;
		$city = $user->town;
		$state = $user->state;
		$street = $user->street;
		$house = $user->house;
		$korpus =$user->korpus;
		$flat = $user->flat;

		set_include_path(CURRENT_DIR.'/../library/PHPExcel/Classes'.
		PATH_SEPARATOR . get_include_path());
		/** Error reporting */
		error_reporting(E_ALL&~E_NOTICE);
		include("PHPExcel.php");
		include_once 'PHPExcel/IOFactory.php';
		$objPHPExcel = PHPExcel_IOFactory::load(
		CURRENT_DIR."/../config/post_print_template.xls");
		$objPHPExcel->setActiveSheetIndex(0);
		$aSheet = $objPHPExcel->getActiveSheet();

		$summ2strFont = array(
			'font'=>array(
				'name'=>'Arial',
				'bold'=>true,
				'itallic'=>true,
				'colorIndex'=>62,
				'size'=>11.5
			)
		);
		$summ2strFont_second = array(
			'font'=>array(
				'name'=>'Arial',
				'bold'=>true,
				'itallic'=>true,
				'colorIndex'=>62,
				'size'=>13
			)
		);
		if(strlen(self::summ2str($order->summa))>37){
			$summ2strFont['font']['size'] = $summ2strFont['font']['size']
			-intval((strlen(self::summ2str($order->summa))-27)/6);
			$summ2strFont_second['font']['size'] = $summ2strFont_second['font']['size']
			-intval((strlen(self::summ2str($order->summa))-27)/10);
		}
		$aSheet->setCellValue('C16',
		self::summ2str($order->summa))->getStyle('C16')->applyFromArray($summ2strFont);
		$aSheet->setCellValue('X16',
		self::summ2str($order->summa))->getStyle('X16')->applyFromArray($summ2strFont_second);
		$aSheet->setCellValue('AK13',$order->summa);
		$aSheet->setCellValue('L21',$order->summa);
		$aSheet->setCellValue('Y38',$order->summa);
		$aSheet->setCellValue('AL43',$order->summa);
		$aSheet->setCellValue('L49',$order->summa);

		//index
		$aSheet->setCellValue('D23', $index[0]);
		$aSheet->setCellValue('E23', $index[1]);
		$aSheet->setCellValue('F23', $index[2]);
		$aSheet->setCellValue('G23', $index[3]);
		$aSheet->setCellValue('H23', $index[4]);
		$aSheet->setCellValue('I23', $index[5]);

		$aSheet->setCellValue('Y27', $index[0]);
		$aSheet->setCellValue('Z27', $index[1]);
		$aSheet->setCellValue('AA27', $index[2]);
		$aSheet->setCellValue('AB27', $index[3]);
		$aSheet->setCellValue('AC27', $index[4]);
		$aSheet->setCellValue('AD27', $index[5]);

		$aSheet->setCellValue('Y45', $index[0]);
		$aSheet->setCellValue('Z45', $index[1]);
		$aSheet->setCellValue('AA45', $index[2]);
		$aSheet->setCellValue('AB45', $index[3]);
		$aSheet->setCellValue('AC45', $index[4]);
		$aSheet->setCellValue('AD45', $index[5]);

		$aSheet->setCellValue('D52', $index[0]);
		$aSheet->setCellValue('E52', $index[1]);
		$aSheet->setCellValue('F52', $index[2]);
		$aSheet->setCellValue('G52', $index[3]);
		$aSheet->setCellValue('H52', $index[4]);
		$aSheet->setCellValue('I52', $index[5]);

		/*$aSheet->setCellValue('AK45', $index[0]);
		$aSheet->setCellValue('AL45', $index[1]);
		$aSheet->setCellValue('AM45', $index[2]);
		$aSheet->setCellValue('AN45', $index[3]);
		$aSheet->setCellValue('AO45', $index[4]);
		$aSheet->setCellValue('AP45', $index[5]);*/


		//adress
		$font_x47 = array(
			'font'=>array(
				'name'=>'Arial Cyr',
				'bold'=>true,
				'italic'=>true,
				'size'=>10,
				'colorIndex'=>62
			)
		);

		$aSheet->setCellValue('C25', $country.', '.$state.', '.$city);
		$aSheet->setCellValue('X28', $country.', '.$state.', '.$city);
		//$aSheet->setCellValue('J30', $country.', '.$state.', '.$city);
		if(mb_strlen($country.', '.$state.', '.$city,'utf-8')>27){
			$font_x47['font']['size'] = $font_x47['font']['size']
			-intval((mb_strlen($country.', '.$state.', '.$city,'utf-8')-20)/5);
		}
		$aSheet->setCellValue('X47', $country.', '.$state.', '.$city)
		->getStyle('X47')->applyFromArray($font_x47);
		$aSheet->setCellValue('C54', $country.', '.$state.', '.$city);

		$aSheet->setCellValue('C26', $street.', '.$house.'-'.(!empty($korpus)?$korpus.
		'-':'').$flat);
		$aSheet->setCellValue('X30', $street.', '.$house.'-'.(!empty($korpus)?$korpus.
		'-':'').$flat);
		//$aSheet->setCellValue('C32', $street.', '.$house.'-'.(!empty($korpus)?$korpus.
		//'-':'').$flat);
		$aSheet->setCellValue('X49', $street.', '.$house.'-'.(!empty($korpus)?$korpus.
		'-':'').$flat);
		$aSheet->setCellValue('C55', $street.', '.$house.'-'.(!empty($korpus)?$korpus.
		'-':'').$flat);


		//кому
		/*include_once 'names.php';
		$a = new RussianNameProcessor($name_utf);*/
		$aSheet->setCellValue('Y25',$name);
		$aSheet->setCellValue('D27',$name);
		$aSheet->setCellValue('D56',$name);
		$aSheet->setCellValue('Y41', $user->name_f.' '.strtoupper(substr($user->name_i,0,1).
		'.'.substr($user->name_o, 0,1).'.'));


		//call the files needed and out put it to the client
		include("PHPExcel/Writer/Excel5.php");
		$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="print.xls"');
		header('Cache-Control: max-age=0');
		$objWriter->save('php://output');

		$this->view->layout()->disableLayout();
	}

	public static function summ2str($inn, $stripkop=false) {
     $nol = 'ноль';
     $str[100]= array('','сто','двести','триста','четыреста','пятьсот','шестьсот', 'семьсот', 'восемьсот','девятьсот');
     $str[11] = array('','десять','одиннадцать','двенадцать','тринадцать', 'четырнадцать','пятнадцать','шестнадцать','семнадцать', 'восемнадцать','девятнадцать','двадцать');
     $str[10] = array('','десять','двадцать','тридцать','сорок','пятьдесят', 'шестьдесят','семьдесят','восемьдесят','девяносто');
     $sex = array(
         array('','один','два','три','четыре','пять','шесть','семь', 'восемь','девять'),// m
         array('','одна','две','три','четыре','пять','шесть','семь', 'восемь','девять') // f
     );
     $forms = array(
         array('копейка', 'копейки', 'копеек', 1), // 10^-2
         array('рубль', 'рубля', 'рублей',  0), // 10^ 0
         array('тысяча', 'тысячи', 'тысяч', 1), // 10^ 3
         array('миллион', 'миллиона', 'миллионов',  0), // 10^ 6
         array('миллиард', 'миллиарда', 'миллиардов',  0), // 10^ 9
         array('триллион', 'триллиона', 'триллионов',  0), // 10^12
     );
     $out = $tmp = array();
     // Поехали!
     $tmp = explode('.', str_replace(',','.', $inn));
     $rub = number_format($tmp[ 0], 0,'','-');
     if ($rub== 0) $out[] = $nol;
     // нормализация копеек
     $kop = isset($tmp[1]) ? substr(str_pad($tmp[1], 2, '0', STR_PAD_RIGHT), 0,2) : '00';
     $segments = explode('-', $rub);
     $offset = sizeof($segments);
     if ((int)$rub== 0) { // если 0 рублей
         $o[] = $nol;
         $o[] = self::morph( 0, $forms[1][ 0],$forms[1][1],$forms[1][2]);
     }
     else {
         foreach ($segments as $k=>$lev) {
             $sexi= (int) $forms[$offset][3]; // определяем род
             $ri = (int) $lev; // текущий сегмент
             if ($ri== 0 && $offset>1) {// если сегмент==0 & не последний уровень(там Units)
                 $offset--;
                 continue;
             }
             // нормализация
             $ri = str_pad($ri, 3, '0', STR_PAD_LEFT);
             // получаем циферки для анализа
             $r1 = (int)substr($ri, 0,1); //первая цифра
             $r2 = (int)substr($ri,1,1); //вторая
             $r3 = (int)substr($ri,2,1); //третья
             $r22= (int)$r2.$r3; //вторая и третья
             // разгребаем порядки
             if ($ri>99) $o[] = $str[100][$r1]; // Сотни
             if ($r22>20) {// >20
                 $o[] = $str[10][$r2];
                 $o[] = $sex[ $sexi ][$r3];
             }
             else { // <=20
                 if ($r22>9) $o[] = $str[11][$r22-9]; // 10-20
                 elseif($r22> 0) $o[] = $sex[ $sexi ][$r3]; // 1-9
             }
             // Рубли
             $o[] = self::morph($ri, $forms[$offset][ 0],$forms[$offset][1],$forms[$offset][2]);
             $offset--;
         }
     }
     // Копейки
     if (!$stripkop) {
        $o[] = $kop;
         $o[] = self::morph($kop,$forms[ 0][ 0],$forms[ 0][1],$forms[ 0][2]);
     }
     return preg_replace("/\s{2,}/",' ',implode(' ',$o));
 }

  /**
 * Склоняем словоформу
 */
 public static function morph($n, $f1, $f2, $f5) {
     $n = abs($n) % 100;
     $n1= $n % 10;
     if ($n>10 && $n<20) return $f5;
     if ($n1>1 && $n1<5) return $f2;
     if ($n1==1) return $f1;
     return $f5;
	}
	
	public function exportAction() {
		// FIXED реализовать экспорт заказов;

		CmsAuth::check();

		$orders = MF_Main::getInstance()->OrderList;
		$orderSearch = $orders->OrderSearch();

        /*
         * лимиты отбрасываем
         * if ((NULL !== $limit_from = $this->getRequest()->getParam('limit_from'))
			&& (NULL !== $limit_amount = $this->getRequest()->getParam('limit_amount'))) {
				$orderSearch->setLimits($limit_from,$limit_amount);
        }*/

        $orderSearch->flag->value = ">0"; //корзины отбрасываем
        //берем фильтр
        if( NULL !== $f_status = $this->getRequest()->getParam('f_status') ){
            if( $f_status )
                $orderSearch->flag->$f_status = 1;
        }

        if( NULL !== $f_login = $this->getRequest()->getParam('f_login') ){
            $d = "b.login";
            $orderSearch->$d = $f_login;
        }

		if ((NULL !== $from_date = $this->getRequest()->getParam('f_from'))
			&& (NULL !== $to_date = $this->getRequest()->getParam('f_to'))) {
				$orderSearch->dateFromTo($from_date,$to_date);
		}

		$orderSearch->Make();

		//формируем массив с данными
		$orders_data = array();

		//в качестве индексов = key
		$fNames = $orders->getFlagNames(); //русские названия
		$fBits = $orders->getFlagBits();   //номера битов

		$this->view->flagNames = $fNames;

		for($i=0; $i<$orderSearch->length(); $i++){
            $ordersNoteNode = array();
			$ordersNote = $orderSearch->item($i);
            //сформируем массив с флагами
            $users = MF_Main::getInstance()->UserList->UserSearch();
            $users->user_id = $ordersNote->user_id;
            $users->Make();

            $ordersNoteNode['orders_goods'] = array();
			for ($g=0;$g<$ordersNote->length();$g++) {
				$good = $ordersNote->item($g);
				array_push($ordersNoteNode['orders_goods'],
					array(
						'item_id' => $good->item_id,
						'name' => $good->name,
						'price' => $good->price,
						'count' => $good->count
					));

			}

            $dt = explode(' ', $ordersNote->date_time);
             $ordersNoteNode['order_date']=
             array('id' => $ordersNote->order_id,
                    	'date' => $dt[0],
                		'time'=>$dt[1]
                		);
                    $ordersNoteNode['users_login']=
                    array('id' => $ordersNote->order_id, 'user_id' => $users->item(0)->user_id, 'value' => $users->item(0)->login."(id: ".$users->item(0)->user_id.")");
                    $ordersNoteNode['orders_status']=
                    array('id' => $ordersNote->order_id, 'value' => $ordersNote->flagAsKey(),
                        'flagNames' => $fNames, 'bitName' => $fBits );
                    $ordersNoteNode['order_summa']=
                    array('id' => $ordersNote->order_id,'value' => $ordersNote->summa);
                    $ordersNoteNode['user_adress']=
                    	array(
                    		'index'=>$users->item(0)->index2,
                    		'state'=>$users->item(0)->state,
                    		'town'=>$users->item(0)->town,
                    		'street'=>$users->item(0)->street,
                    		'house'=>$users->item(0)->house,
                    		'korpus'=>$users->item(0)->korpus,
                    		'flat'=>$users->item(0)->flat
                    	);
                    $ordersNoteNode['user_name']=
                    	array(
                    		'name_f'=>$users->item(0)->name_f,
                    		'name_i'=>$users->item(0)->name_i,
                    		'name_o'=>$users->item(0)->name_o,
                    		'phone'=>$users->item(0)->phone,
                    		'art_code'=>$users->item(0)->art_code
                    	);

            //пройдемся по флагам и, если выставлен, занести его в массив юзера
/*			foreach($fBits as $index => $c ){
				array_push($ordersNoteNode,
				    array('order_flags',
				        array('id' => $ordersNote->order_id, 'bit' => $index, 'value' => $ordersNote->flag->$index)
				));
			}*/

            array_push($orders_data, $ordersNoteNode);
            unset($users);
		}

		set_include_path(CURRENT_DIR.'/../library/PHPExcel/Classes'.
		PATH_SEPARATOR . get_include_path());
		/** Error reporting */
		error_reporting(E_ALL&~E_NOTICE);
		include("PHPExcel.php");
		include_once 'PHPExcel/IOFactory.php';
		$objPHPExcel = PHPExcel_IOFactory::load(
		CURRENT_DIR."/../config/order_list_template.xls");
		$objPHPExcel->setActiveSheetIndex(0);
		$aSheet = $objPHPExcel->getActiveSheet();
		$aSheet->setTitle('Экспорт');

		//fonts
		$baseFont = array(
			'font'=>array(
				'name'=>'Calibri',
				'size'=>'11',
				'bold'=>false,
				'colorIndex'=>8
			),
			'alignment'=>array(
				'horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_LEFT,
				'vertical'=>PHPExcel_Style_Alignment::VERTICAL_TOP,
				'wrapText'=>true
			)
		);

		$dateFont = array(
			'font'=>array(
				'name'=>'Arial',
				'size'=>10,
				'bold'=>false,
				'colorIndex'=>32767
			)
		);

		$goodsFont = array(
			'font'=>array(
				'name'=>'Arial',
				'size'=>8,
				'bold'=>false
			),
			'alignment'=>array(
				'wrapText'=>true,
				'horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_LEFT
			)
		);

		$row = 2;
		for($i=0;$i<count($orders_data);$i++){
			$row++;
			//set height
			$aSheet->getRowDimension($row)->setRowHeight(20.1);
			$aSheet->getStyle('A'.$row)->applyFromArray($baseFont);
			$aSheet->getStyle('B'.$row)->applyFromArray($baseFont);
			$aSheet->setCellValue('A'.$row,$i+1);

			$goods = $orders_data[$i]['orders_goods'];
			$g_count = count($goods)-1;

			$aSheet->mergeCells('A'.$row.':A'.($row+$g_count));
			$aSheet->mergeCells('B'.$row.':B'.($row+$g_count));

			for($k=0;$k<count($goods);$k++){

				$aSheet->setCellValue('C'.($row+$k),
				$goods[$k]['name']);
				$aSheet->getStyle('C'.($row+$k))->applyFromArray(
				$goodsFont);
				$aSheet->setCellValue('H'.($row+$k),
				$goods[$k]['count']);
				$aSheet->getStyle('H'.($row+$k))->applyFromArray(
				$goodsFont);
				$aSheet->setCellValue('I'.($row+$k),
				$goods[$k]['price']);
				$aSheet->getStyle('I'.($row+$k))->applyFromArray(
				$goodsFont);

			}

			/*$aSheet->setCellValue('C'.$row, 
			$g_data);*/
			//$aSheet->getStyle('C'.$row)->applyFromArray($goodsFont);

			$aSheet->setCellValue('J'.$row, 
			$orders_data[$i]['order_summa']['value']);
			$aSheet->mergeCells('J'.$row.':J'.($row+$g_count));
			$aSheet->setCellValue('K'.$row, 
			$orders_data[$i]['user_adress']['index']);
			$aSheet->mergeCells('K'.$row.':K'.($row+$g_count));
			$aSheet->setCellValue('L'.$row, 
			$orders_data[$i]['user_adress']['state']);
			$aSheet->mergeCells('L'.$row.':L'.($row+$g_count));
			$aSheet->setCellValue('M'.$row, 
			$orders_data[$i]['user_adress']['town']);
			$aSheet->mergeCells('M'.$row.':M'.($row+$g_count));
			$aSheet->setCellValue('N'.$row, 
			$orders_data[$i]['user_adress']['street']);
			$aSheet->mergeCells('N'.$row.':N'.($row+$g_count));
			$aSheet->setCellValue('O'.$row, 
			$orders_data[$i]['user_adress']['house']);
			$aSheet->mergeCells('O'.$row.':O'.($row+$g_count));
			$aSheet->setCellValue('P'.$row, 
			$orders_data[$i]['user_adress']['korpus']);
			$aSheet->mergeCells('P'.$row.':P'.($row+$g_count));
			$aSheet->setCellValue('Q'.$row, 
			$orders_data[$i]['user_adress']['flat']);
			$aSheet->mergeCells('Q'.$row.':Q'.($row+$g_count));
			$aSheet->setCellValue('R'.$row, 
			$orders_data[$i]['user_name']['phone']);
			$aSheet->mergeCells('R'.$row.':R'.($row+$g_count));
			$aSheet->setCellValue('S'.$row, 
			$orders_data[$i]['user_name']['name_f']);
			$aSheet->mergeCells('S'.$row.':S'.($row+$g_count));
			$aSheet->setCellValue('T'.$row, 
			$orders_data[$i]['user_name']['name_i']);
			$aSheet->mergeCells('T'.$row.':T'.($row+$g_count));
			$aSheet->setCellValue('U'.$row, 
			$orders_data[$i]['user_name']['name_o']);
			$aSheet->mergeCells('U'.$row.':U'.($row+$g_count));
			$aSheet->mergeCells('V'.$row.':V'.($row+$g_count));


			//Статус
			$rus_status = '';
			switch($orders_data[$i]['orders_status']['value']){

				case 'nonsubmit':
					$rus_status='Не подтвержден';
				break;
				case 'submit':
					$rus_status='Подтвержден';
				break;
				case 'inwork':
					$rus_status='На исполнении';
				break;
				case 'send':
					$rus_status='Выслан';
				break;
				case 'cancelbyuser':
					$rus_status='Отменен пользователем';
				break;
				default:
					$rus_status='Отменен администрацией';
				break;

			}

			$aSheet->setCellValue('X'.$row, 
			$rus_status);
			$aSheet->getStyle('X'.$row)->applyFromArray($baseFont);
			$aSheet->mergeCells('X'.$row.':X'.($row+$g_count));
			$row+=$g_count;


		}
		//call the files needed and out put it to the client
		include("PHPExcel/Writer/Excel5.php");
		$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="print.xls"');
		header('Cache-Control: max-age=0');
		$objWriter->save('php://output');

		$this->view->layout()->disableLayout();

	}
	
}